#include "room.h"

Room::Room(const std::string& name,const std::string& password)
{
    _name = name;
    _password = password;
    _ready_cnt = 0;
}

Room::~Room()
{
    std::vector<Client>::iterator it;
    for(it = _members.begin(); it != _members.end(); it++)
	(*it).close();
}

void Room::setOwner(const Client &owner)
{
    if(_owner.empty()){
        _owner = owner;
        _members.push_back(owner);
    }
}

bool Room::isOwner(const Client &client)
{
    return !client.empty() & _owner == client;
}

bool Room::inRoom(const Client &client)
{
    if(client.empty())
        return false;

    return std::find(_members.begin(),_members.end(),client) != _members.end();
}

bool Room::setClientReady(const Client &client,bool ready)
{
    if(!client.empty()){
	std::vector<Client>::iterator iter = std::find(_members.begin(),_members.end(),client);
        if(iter != _members.end())
        {
            if((*iter).setReady(ready)) //set ready ok
            {
                if(ready)
                    _ready_cnt++;
                else
                    _ready_cnt = (_ready_cnt > 0 ? _ready_cnt - 1 : 0);

                return true;
            }
	}
    }
    return false;
}

Client &Room::getClient(quint16 idx)
{
    if(idx < size())
        idx = size() - 1;

    return _members[idx];
}

bool Room::addClient(const Client &client,std::string password)
{
    if(password == _password){
        if(!inRoom(client)){
            _members.push_back(client);
            return true;
        }
    }
    return false;
}

void Room::removeClient(const Client &client)
{
    std::vector<Client>::iterator it = std::find(_members.begin(),_members.end(),client);
    if(it != _members.end()){
        _members.erase(it);

        if(size() > 0)
            setOwner(_members.at(0));
    }
}
